<?php

namespace App\Http\Controllers\Api\Promotion;

use Illuminate\Http\Request;

use Carbon\Carbon;

use App\Http\Controllers\Controller;

use App\Models\Promotion\Seckill;

use Illuminate\Support\Facades\Redis as Redis;

use App\Models\ConfigureFunction; //功能配置表

use App\Models\Mall\MallMaster;

use App\Service\WdhService;

use App\Service\Checkout\SeckillCheckoutService;

use App\Models\Wx\WxCustomer;  //微信会员表

use App\Models\Customer\Customer;

use App\Models\Deliver\Deliver;

class SeckillCheckoutController extends Controller
{

    //购物车数组
    private $sec_kill_bill_data;

    /**
     * 结算
     * @param Request $req
     * @param Response $res
     * @return mixed
     */
    private function checkBill($pcustID, $data = null)
    {

        //实例化团购结算类
        $sec_checkout_service = new SeckillCheckoutService();

        $result = $sec_checkout_service->checkout($this->sec_kill_bill_data);
        if ( $result['code'] != 200 ) {
            return array(
                'code' => 400,
                'message' => $result['message']
            );
        }

        $return_array['checkout'] = $result['data'][1];

        if ( $data ) {
            $return_array = array_merge($return_array, $data);
        }

        Redis::setex('G_SEC_KILL_' . $pcustID, 360000, json_encode($result['data'][0], true));

        return array(
            'code' => 200,
            'message' => 'ok',
            'data' => $return_array
        );

    }

    /**
     * 初始化秒杀结算页
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|\Symfony\Component\HttpFoundation\Response
     */
    public function init(Request $request){

        $session_id = $request->input('session_id', session_id());
        $platform = $request->input('platform', 6);
        $mallID = $request->input('mallID', 1);

        if (empty($session_id)) {
            return response()->json(['code' => 100001, 'message' => '缺少参数：session_id']);
        }

        $pcustID = get_customer_id($session_id, $platform);
        if (!$pcustID) {
            return response()->json(['code' => 100002, 'message' => '请登录']);
        }

        $check_data = [
            'config_id' => 0,
            'is_send' => 0,
            'cust_deliver_id' => 0,
            'zt_mobile' => 0,
            'zt_cust_name' => 0,
            'send_limit_money' => 0,
            'is_zt_time' => 0,
            'is_send_time' => 0,
            'is_use_balance' => 0,
            'is_use_points' => 0,
            'is_sec_kill' => 0,
            'is_mall' => 0,
            'send_type' => [
                '1' => [
                    'name' => '送货上门',
                    'selected' => 0
                ],
                '2' => [
                    'name' => '门店自提',
                    'selected' => 1
                ]
            ]
        ];

        //获取秒杀购物车信息
        $sec_kill_order = json_decode(Redis::get('G_SEC_KILL_' . $pcustID), true);
        if (!$sec_kill_order) {
            return response()->json(['code' => 200, 'message' => 'ok', 'data' => ['is_sec_kill' => 1]]);
        }
        $promotion_id = $sec_kill_order['activity_id'];

        //获取秒杀信息
        $sec_kill = Seckill::getCache($promotion_id);
        if (!$sec_kill) {
            return response()->json(['code' => 200, 'message' => 'ok', 'data' => ['is_tuan' => 1]]);
        }

        //查询会员信息
        $customer = Customer::select('pcustID', 'custID', 'cardNo')->find($pcustID);
        if (!$customer) {
            return response()->json(['code' => 200, 'message' => 'ok', 'data' => ['is_sec_kill' => 1]]);
        }

        //查询微信公众号粉丝信息，用于查询会员账户余额和积分
        $wechat_customer = WxCustomer::where(['pcustID'=> $pcustID])->first();
        if ($wechat_customer) {
            $openId = $wechat_customer->openId;
        } else {
            $openId = '';
        }


        /**
         * 微信支付方式类型  1、普通版 2、代理版
         */

        $check_data['wechat_pay_type'] = ConfigureFunction::getConfigureField(9, 'wechat_pay_type');

        /**
         * ===============================================
         * 获取结算配置
         * ===============================================
         */
        $checkout_config = $sec_kill['config'];
        if (!$checkout_config) {
            return response()->json(['code' => 200, 'message' => 'ok', 'data' => ['is_tuan' => 1]]);
        }
        $check_data['config_id'] = $checkout_config['config_id'];

        /**
         * ====================================
         * 配送方式
         * ====================================
         */
        $send_type_data = explode(',', $checkout_config['send_type']);
        foreach ( $check_data['send_type'] as $key=>$item ) {
            if ( !in_array($key, $send_type_data) ) {
                unset($check_data['send_type'][$key]);
            }
        }

        //实例化秒杀结算类
        $sec_checkout_service = new SeckillCheckoutService();

        /**
         * ==========================================
         * 选店
         * ==========================================
         */
        $deliver_id = 0;
        $is_open_choose_mall = ConfigureFunction::getConfigureField(8, 'is_open_choose_mall');
        $check_data['is_select_mall'] = $is_open_choose_mall;

        if ($is_open_choose_mall == 1) { //选店模式

            //判断是否有选择门店
            if (!ebsig_is_int($mallID)) {
                return response()->json(['code' => 200, 'message' => 'ok', 'data' => ['is_tuan' => 1]]);
            }

            //查询门店信息
            $mall = MallMaster::getCache($mallID);
            if (!$mall) {
                return response()->json(['code' => 100003, 'message' => '门店不存在']);
            }

            //判断自提支持
            if (isset($mall['mention']) && $mall['mention'] == 0) {
                unset($checkout_config['send_type']['2']);
            }

            //判断配送支持
            if (isset($mall['mall_is_send']) && $mall['mall_is_send'] == 0) {
                unset($checkout_config['send_type']['1']);
            }

            $check_data['send_limit_money'] = $mall['send_limit_money'];

            $zt_id = 0;
            $zt_name = '';
            $zt_code = '';
            $mallName = $mall['mallName'];
            $mallCode = $mall['mallCode'];
            if ($mall['mallType'] == 2) {
                $zt_id = $mall['mallID'];
                $zt_name = $mall['mallName'];
                $zt_code = $mall['mallCode'];
            }

            //查询会员地址信息
            $deliver = Deliver::where(['pcustID' => $pcustID, 'mallID' => $mallID, 'zt_id' => $zt_id])->first();
            if (!$deliver) {
                $deliver_id = generate_seqno('seqno_custdeliver', true);
                $deliver = new Deliver();
                $deliver->uuid = makeUuid();
                $deliver->timeStamp = Carbon::now();
                $deliver->creator = 'system';
                $deliver->createTime = Carbon::now();
                $deliver->deliverID = $deliver_id;
                $deliver->pcustID = $pcustID;
                $deliver->provinceName = $mall['provinceName'];
                $deliver->cityName = $mall['cityName'];
                $deliver->countyName = $mall['countyName'];
                $deliver->provinceid = $mall['provinceid'];
                $deliver->cityid = $mall['cityid'];
                $deliver->countyid = $mall['countyid'];
                $deliver->address = $mall['address'];
                $deliver->custname = isset($customer->custname) ? $customer->custname : '';
                $deliver->postalCode = '';
                $deliver->mobile = $mall['mobile'];
                $deliver->phone = $mall['phone'];
                $deliver->mallID = $mallID;
                $deliver->mallName = $mallName;
                $deliver->mallCode = $mallCode;
                $deliver->is_default = 0;
                $deliver->zt_name = $zt_name;
                $deliver->zt_code = $zt_code;
                $deliver->save();
            } else {
                $deliver_id = $deliver->deliverID;
            }

        }

        if ( count($check_data['send_type']) == 1 ) {
            if ( isset($check_data['send_type']['1']) ) {
                $check_data['send_type']['1']['selected'] = 1;
                $sec_kill_order['ziti'] = 0;
            }
            if ( isset($check_data['send_type']['2']) ) {
                $check_data['send_type']['2']['selected'] = 1;
                $sec_kill_order['ziti'] = 1;
            }
        }


        /**
         * ===============================================
         * 生成默认地址信息
         * ===============================================
         */
        if (in_array(1, $send_type_data)) {
            $res = $sec_checkout_service->getAddress($sec_kill_order, 0, $deliver_id, $pcustID);
            if ($res) {
                $check_data['deliver'] = $res[0];
                $sec_kill_order = $res[1];
            }

        }

        /**
         * ===============================================
         * 生成默认门店信息
         * ===============================================
         */
        if (in_array(2, $send_type_data)) {
            $res = $sec_checkout_service->getAddress($sec_kill_order, 1, $deliver_id, $pcustID, null, $mallID);
            if ($res) {
                $check_data['mall'] = $res[0];
                $sec_kill_order = $res[1];
            }

        }


        /**
         * ===============================================
         * 提货时间
         * ===============================================
         */
        $check_data['ziti_time'] = $sec_checkout_service->order_time_func(13);
        if ( !empty($check_data['ziti_time']) ) {
            $check_data['is_zt_time'] = 1;
        }


        /**
         * ===============================================
         * 配送时间
         * ===============================================
         */
        $check_data['send_time'] = $sec_checkout_service->order_time_func(12);
        if ( !empty($check_data['send_time']) ) {
            $send_time_type = 1;
            foreach($check_data['send_time'] as $t) {
                if (!isset($t['id']))
                    $send_time_type = 2;
            }
            $check_data['send_time'] = [
                'send_time_type' => $send_time_type,
                'send_time_list' => $check_data['send_time']
            ];
            $check_data['is_send_time'] = 1;
        }

        /**
         * ===============================================
         * 提货条件
         * ===============================================
         */
        $pick_up_goods_conditions = explode(',', $checkout_config['pick_up_goods_conditions']);
        if (in_array(1, $pick_up_goods_conditions)) {
            $check_data['zt_mobile'] = 1;
        }
        if (in_array(3, $pick_up_goods_conditions)) {
            $check_data['zt_cust_name'] = 1;
        }

        //获取提货人姓名和提货人手机号信息
        $cust_ziti_info_json = Redis::get('CUST_ZITI_INFO_' . $pcustID);
        if ( $cust_ziti_info_json ) {
            $cust_ziti_info = json_decode($cust_ziti_info_json, true);
            if ( $cust_ziti_info ) {
                $check_data['cust_mobile'] = isset($cust_ziti_info['cust_mobile']) ? $cust_ziti_info['cust_mobile'] : '';
                $check_data['cust_name'] = isset($cust_ziti_info['cust_name']) ? $cust_ziti_info['cust_name'] : '';
            }
        }

        /**
         * ===============================================
         * 商品
         * ===============================================
         */
        $check_data['goods'] = [
            'goodsName' => $sec_kill_order['goods'][0]['goodsName'],
            'goods_amount' => $sec_kill_order['goods'][0]['goods_amount'],
            'pic' => $sec_kill_order['goods'][0]['pic'],
            'price' => $sec_kill_order['goods'][0]['price']
        ];

        /**
         * ===============================================
         * 支付方式
         * ===============================================
         */
        $check_data['pay_type'] = $sec_checkout_service->getPayType($checkout_config['pay_type']);
        if ( in_array(2, explode(',', $checkout_config['pay_type'])) ) {
            $check_data['is_use_balance'] = 1;
        }
        if ( in_array(3, explode(',', $checkout_config['pay_type'])) ) {
            $check_data['is_use_points'] = 1;
        }

        /**
         * ===============================================
         * 会员余额
         * ===============================================
         */
        $check_data['balance'] = 0;
        if ( $check_data['is_use_balance'] == 1 ) {
            $args_data = array(
                'pcustID' => $pcustID,
                'cardNo'  => $customer->cardNo
            );
            $check_data['balance'] = WdhService::balance( $args_data );
        }

        /**
         * ===============================================
         * 会员积分
         * ===============================================
         */
        $check_data['exchange_rate'] = $exchange_rate = ConfigureFunction::getConfigureField(2, 'points_exchange_ratio', 100);;
        $check_data['points'] = 0;
        $check_data['points_cash'] = 0;
        if ( $check_data['is_use_points'] == 1 ) {
            $args_data = array(
                'pcustID' => $pcustID,
                'openId'  => $openId,
                'cardNo'  => $customer->cardNo
            );
            $points = WdhService::points( $args_data );
            $check_data['points'] = $points;
            $check_data['points_cash'] = 0;
            if ( $points > 0 ) {
                $check_data['points_cash'] = floor(($points / $exchange_rate) * 100) / 100;
            }
        }

        /**
         * ===============================================
         * 结算信息
         * ===============================================
         */
        $res = $sec_checkout_service->checkout($sec_kill_order);
        if ($res['code'] != 200) {
            return response()->json(['code' => $res['code'], 'message' => $res['message']]);
        }
        $sec_kill_order = $res['data'][0];
        $check_data['checkout'] = $res['data'][1];

        Redis::setex('G_SEC_KILL_' .  $pcustID, 360000, json_encode($sec_kill_order, true));

        return response()->json(['code' => 200, 'message' => 'ok', 'data' => $check_data]);

    }

    /**
     * 选择收货地址
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|\Symfony\Component\HttpFoundation\Response
     */
    public function chooseAddress(Request $request)
    {

        $deliverID = $request->input('deliverID');
        $sendTypeID = $request->input('sendTypeID');
        $latitude = $request->input('latitude');
        $longitude = $request->input('longitude');
        $session_id = $request->input('session_id', session_id());
        $mallID = $request->input('mallID');
        $platform = $request->input('platform', 6);


        if (empty($session_id)) {
            return response()->json(['code' => 400, 'message' => '缺少参数：session_id']);
        }

        $pcustID = get_customer_id($session_id, $platform);
        if (!$pcustID) {
            return response()->json(['code' => 400, 'message' => '请登录']);
        }

        if (!ebsig_is_int($deliverID, 2)) {
            return response()->json(['code' => 400, 'message' => '缺少参数：deliverID']);
        }

        //实例化团购结算类
        $sec_checkout_service = new SeckillCheckoutService();

        //获取购物车信息
        $this->sec_kill_bill_data = json_decode(Redis::get('G_SEC_KILL_' . $pcustID), true);
        if (!$this->sec_kill_bill_data) {
            return response()->json(['code' => 400, 'message' => '暂无订单信息']);
        }

        //配送方式
        if (isset($sendTypeID) && ebsig_is_int($sendTypeID)) {
            $send_data = $sec_checkout_service->getSend($this->sec_kill_bill_data, $sendTypeID);
            if($send_data){
                $this->sec_kill_bill_data = $send_data[1];
            }
        }

        //查询会员收货地址
        $deliver_data = $sec_checkout_service->getDeliver( $this->sec_kill_bill_data, $pcustID, $deliverID );
        if (!$deliver_data) {
            return response()->json(['code' => 400, 'message' => '收货地址信息没有找到，请选择其他收货地址']);
        }

        $is_open_choose_mall = ConfigureFunction::getConfigureField(8,'is_open_choose_mall');
        if ($is_open_choose_mall == 1) {

            if ( !ebsig_is_int($mallID) ) {
                return response()->json(['code' => 400, 'message' => '请选择门店']);
            }
            /**
             * ===========start检查门店配送范围==============
             */
            if (!empty($latitude) && !empty($longitude)) {
                $result_array = WdhService::checktrictSendRange(array('mallID' => $mallID, 'longitude' => $longitude, 'latitude' => $latitude));
                if ($result_array['code'] != 200) {
                    return response()->json(['code' => $result_array['code'], 'message' => $result_array['message']]);
                }
            }
            /**
             * ===========end检查门店配送范围==============
             */

        }


        $this->sec_kill_bill_data = $deliver_data[1];
        $return_array['deliver'] = $deliver_data[0];

        //计算价格
        $return_array = $this->checkBill($pcustID, $return_array['deliver']);

        if ( $return_array['code'] != 200 ) {
            return response()->json(['code' => 400, 'message' => $return_array['message']]);
        }

        return response()->json(['code' => 200, 'message' => 'ok', 'data' => $return_array['data']]);
    }

    /**
     * 使用积分
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|\Symfony\Component\HttpFoundation\Response
     */
    public function usePoints(Request $request)
    {

        $platform = $request->input('platform', 6);
        $session_id = $request->input('session_id', session_id());
        if (empty($session_id)) {
            return response()->json(['code' => 400, 'message' => '缺少参数：session_id']);
        }

        $pcustID = get_customer_id($session_id, $platform);
        if (!$pcustID) {
            return response()->json(['code' => 400, 'message' => '请登录']);
        }

        $use_points = $request->input('use_points');//使用积分

        //获取购物车信息
        $this->sec_kill_bill_data = json_decode(Redis::get('G_SEC_KILL_' . $pcustID), true);

        if($this->sec_kill_bill_data['bill_payable'] <= 0){
            return response()->json(['code' => 400, 'message' => '订单已付款']);
        }

        $custPointsSet = ConfigureFunction::getConfigure(2);

        $exchange_rate = 100;
        $max_rate = 100;
        if (isset($custPointsSet['points_exchange_ratio'])) {
            $exchange_rate = $custPointsSet['points_exchange_ratio'];
        }
        if (isset($custPointsSet['points_payable_ration'])) {
            $max_rate = $custPointsSet['points_payable_ration'];
        }

        //查询可用积分
        $args_array = array(
            'pcustID' => $pcustID,
            'cardNo' => $this->sec_kill_bill_data['cardNo']
        );
        $points = WdhService::points( $args_array );

        if (!empty($use_points)) {
            if ( !ebsig_is_int($use_points) ) {
                return response()->json(['code' => 400, 'message' => '请输入积分数']);
            } else if ($points < $use_points) {
                return response()->json(['code' => 400, 'message' => '没有足够的积分可用']);
            }
            $points = $use_points;
        }

        $bill_payable_points = $this->sec_kill_bill_data['bill_payable'] * $exchange_rate;
        if ( $bill_payable_points < $points ) {
            $points = $this->sec_kill_bill_data['bill_payable'] * $exchange_rate;
        }

        $points = $bill_payable_points * ($max_rate/100) < $points ? $bill_payable_points * ($max_rate/100) : $points;

        //记录积分使用信息
        $this->sec_kill_bill_data['use_points'] = array(
            'points' => $points,
            'points_cash' => $points > 0 ? floor(($points / $exchange_rate) * 100) / 100 : 0
        );

        //计算价格
        $check_data = $this->checkBill($pcustID);
        if ( $check_data['code'] != 200 ) {
            return response()->json(['code' => 400, 'message' => $check_data['message']]);
        }

        return response()->json(['code' => 200, 'message' => 'ok', 'data' => $check_data['data']['checkout']]);

    }

    /**
     * 使用余额
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|\Symfony\Component\HttpFoundation\Response
     */
    public function useBalance(Request $request)
    {

        $platform = $request->input('platform', 6);
        $session_id = $request->input('session_id', session_id());
        if (empty($session_id)) {
            return response()->json(['code' => 400, 'message' => '缺少参数：session_id']);
        }

        $pcustID = get_customer_id($session_id, $platform);
        if (!$pcustID) {
            return response()->json(['code' => 400, 'message' => '请登录']);
        }

        //获取购物车信息
        $this->sec_kill_bill_data = json_decode(Redis::get('G_SEC_KILL_' . $pcustID), true);
        if ($this->sec_kill_bill_data['bill_payable'] <= 0) {
            return response()->json(['code' => 400, 'message' => '订单已付款']);
        }

        //查询可用余额
        $args_array = array(
            'pcustID' => $pcustID,
            'cardNo' => $this->sec_kill_bill_data['cardNo']
        );
        $balance = WdhService::balance($args_array);

        //当余额大于付款金额
        if ($this->sec_kill_bill_data['bill_payable'] < $balance) {
            $balance = $this->sec_kill_bill_data['bill_payable'];
        }

        //保存余额使用信息
        $this->sec_kill_bill_data['use_balance'] = array(
            'deduct_amount' => $balance
        );

        //计算价格
        $check_data = $this->checkBill($pcustID);

        if ( $check_data['code'] != 200 ) {
            return response()->json(['code' => 400, 'message' => $check_data['message']]);
        }

        return response()->json(['code' => 200, 'message' => 'ok', 'data' => $check_data['data']['checkout']]);

    }

    /**
     * 取消使用积分
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|\Symfony\Component\HttpFoundation\Response
     */
    public function cancelUsePoints(Request $request)
    {
        $platform = $request->input('platform', 6);
        $session_id = $request->input('session_id', session_id());
        if (empty($session_id)) {
            return response()->json(['code' => 400, 'message' => '缺少参数：session_id']);
        }

        $pcustID = get_customer_id($session_id, $platform);
        if (!$pcustID) {
            return response()->json(['code' => 400, 'message' => '请登录']);
        }

        //获取购物车信息
        $this->sec_kill_bill_data = json_decode(Redis::get('G_SEC_KILL_' . $pcustID), true);

        if(isset($this->sec_kill_bill_data['use_points'])){
            unset($this->sec_kill_bill_data['use_points']);
        }

        $check_data = $this->checkBill($pcustID);

        if ( $check_data['code'] != 200 ) {
            return response()->json(['code' => 400, 'message' => $check_data['message']]);
        }

        return response()->json(['code' => 200, 'message' => 'ok', 'data' => $check_data['data']['checkout']]);
    }

    /**
     * 取消使用余额
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|\Symfony\Component\HttpFoundation\Response
     */
    public function cancelUseBalance(Request $request)
    {
        $platform = $request->input('platform', 6);
        $session_id = $request->input('session_id', session_id());
        if (empty($session_id)) {
            return response()->json(['code' => 400, 'message' => '缺少参数：session_id']);
        }

        $pcustID = get_customer_id($session_id, $platform);
        if (!$pcustID) {
            return response()->json(['code' => 400, 'message' => '请登录']);
        }

        //获取购物车信息
        $this->sec_kill_bill_data = json_decode(Redis::get('G_SEC_KILL_' . $pcustID), true);

        if(isset($this->sec_kill_bill_data['use_balance'])){
            unset($this->sec_kill_bill_data['use_balance']);
        }

        $check_data = $this->checkBill($pcustID);

        if ( $check_data['code'] != 200 ) {
            return response()->json(['code' => 400, 'message' => $check_data['message']]);
        }

        return response()->json(['code' => 200, 'message' => 'ok', 'data' => $check_data['data']['checkout']]);
    }

    /**
     * 验证支付密码
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|\Symfony\Component\HttpFoundation\Response
     */
    public function checkPayPwd(Request $request)
    {
        $platform = $request->input('platform', 6);
        $session_id = $request->input('session_id', session_id());
        if (empty($session_id)) {
            return response()->json(['code' => 400, 'message' => '缺少参数：session_id']);
        }

        $pcustID = get_customer_id($session_id, $platform);
        if (!$pcustID) {
            return response()->json(['code' => 400, 'message' => '请登录']);
        }

        $req_data = $request->all();

        if ( !isset($req_data['pwd']) || empty($req_data['pwd']) ) {
            return response()->json(['code' => 400, 'message' => '请输入支付密码']);
        }

        //获取会员信息
        $cust_base_info = Customer::where(['pcustID' => $pcustID])->first();
        if( empty($cust_base_info) ){
            return response()->json(['code' => 400, 'message' => '没有找到会员信息']);
        }
        $cust_base_info = $cust_base_info->toArray();

        $args_array = array(
            'pcustID' => $pcustID,
            'pwd' => $req_data['pwd'],
            'cardNo' => $cust_base_info['cardNo']
        );

        //调取接口验证支付密码
        $result_array = WdhService::checkPwd($args_array);
        if ( $result_array['code'] != 200 ) {
            return response()->json(['code' => $result_array['code'], 'message' => $result_array['message']]);
        }

        return response()->json(['code' => 200, 'message' => 'ok']);

    }

}